#include "MainMenuState.h"
#include "PlayState.h"
#include "Texture.h"
#include "PlayState.h"
#include "ResMgr.h"
#include "StateMgr.h"
#include "Button.h"
#include "Animation.h"
#include "AnimationSprite.h"
#include "GameUtils.h"
#include "ChooseIslandState.h"

#ifdef ANDROID
#include "unistd.h"
#endif

MainMenuState::MainMenuState()
{
}

void MainMenuState::Init()
{
	ResMgr::GetInstance()->LoadMainMenu();
	background = ResMgr::GetInstance()->GetTexture(TID_MAIN_MENU_BACK);
	aniSprite = new AnimationSprite();
	Animation* ani = new Animation(0);
	ani->GenerateAuto(ResMgr::GetInstance()->GetTexture(TID_MENU_BUTTON),
		200, 80, 2, 0, 3, 0);
	aniSprite->AddAnimation(ani);

	bStart = new Button(X_BUTTON, Y_START, BUTTON_WIDTH, BUTTON_HEIGHT);
	bStart->SetImageForTouchUp(aniSprite, 0, 0);
	bStart->SetImageForTouchDown(aniSprite, 0, 1);

	bExit = new Button(X_BUTTON, Y_EXIT, BUTTON_WIDTH, BUTTON_HEIGHT);
	bExit->SetImageForTouchUp(aniSprite, 0, 2);
	bExit->SetImageForTouchDown(aniSprite, 0, 3);
}
void MainMenuState::Render()
{
	background->Render(0, 0);
	bStart->Render();
	bExit->Render();
}

void MainMenuState::TouchDown(int x, int y)
{
	Button* bPressed = 0;

	if(IsPointInRect(x, y, bStart->GetRect()))
		bPressed = bStart;
	if(IsPointInRect(x, y, bExit->GetRect()))
		bPressed = bExit;

	if(bPressed != 0)
	{
		bPressed->TouchDown();
		OnButtonClick(bPressed, BTE_TOUCH_DOWN);
	}
}

void MainMenuState::OnButtonClick(Button* sender, int event)
{
	if(event == BTE_TOUCH_UP)
	{
		if(sender == bStart)
		{
			//StateMgr::GetInstance()->SwitchState(PlayState::GetInstance());
			StateMgr::GetInstance()->SwitchState(new ChooseIslandState());
		}
		else if(sender == bExit)
		{
#ifdef WIN32
			exit(0);
#elif ANDROID
			_exit(0);
#endif
		}
	}
}

void MainMenuState::TouchUp(int x, int y)
{
	Button* bPressed = 0;

	if(bStart->GetIsTouchDown() == true) bPressed = bStart;
	if(bExit->GetIsTouchDown() == true) bPressed = bExit;

	if(bPressed != 0)
	{
		bPressed->TouchUp();
		OnButtonClick(bPressed, BTE_TOUCH_UP);
	}
}

MainMenuState::~MainMenuState()
{
	ResMgr::GetInstance()->UnloadMainMenu();
}